package guis.classroom;

import exceptions.RepositoryException;
import guis.RegisterPanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JTable;

import classes.Classroom;
import classes.Member;

import communication.Facade;

public class EditClassroomWindow extends ClassroomWindow
{
	private static final long	serialVersionUID	= 1032307379765488755L;
	private Classroom			classroom;

	public EditClassroomWindow( JFrame source, RegisterPanel< Classroom > registerPanel, Facade facade )
	{
		super( "Editar Classe", "editar", source, registerPanel, facade );
		createActions();
		loadClassroom();
	}

	private void createActions()
	{
		cancelButton.addActionListener( new ActionListener()
		{

			@Override
			public void actionPerformed( ActionEvent arg0 )
			{
				setVisible( false );
			}

		} );

		actionButton.addActionListener( new ActionListener()
		{

			@Override
			public void actionPerformed( ActionEvent arg0 )
			{
				String name = nameTextField.getText();
				String magazine = magazineTextFild.getText();
				Member titular = ( Member ) titularComboBox.getSelectedItem();
				Member auxiliar = ( Member ) auxiliarComboBox.getSelectedItem();
				int titularId = 0;
				int auxiliarId = 0;
				if ( titular != null )
					titularId = titular.getId();
				if ( auxiliar != null )
					auxiliarId = auxiliar.getId();

				classroom.setName( name );
				classroom.setMagazine( magazine );
				classroom.setTitularTeacherId( titularId );
				classroom.setAuxiliarTeacherId( auxiliarId );
				classroom.setId( classroom.getId() );

				try
				{
					facade.editClassroom( classroom );
					( ( ClassroomPanel ) registerPanel ).loadTable( null );
					setVisible( false );
				}
				catch ( RepositoryException e )
				{

				}
			}

		} );
	}
	
	private void loadClassroom()
	{
		JTable table = registerPanel.getTable();
		int selectedIndex = table.getSelectedRow();
		
		int id = Integer.parseInt( ( String ) table.getModel().getValueAt( selectedIndex, 0 ) );
		String name = ( String ) table.getModel().getValueAt( selectedIndex, 1 );
		String magazine = ( String ) table.getModel().getValueAt( selectedIndex, 2 );
		Member titular = ( Member ) table.getModel().getValueAt( selectedIndex, 3 );
		Member auxiliar = ( Member ) table.getModel().getValueAt( selectedIndex, 4 );
		int titularId = 0;
		int auxiliarId = 0;
		if ( titular != null ) titularId = titular.getId();
		if ( auxiliar != null ) auxiliarId = auxiliar.getId();
		
		this.classroom = new Classroom( name, magazine, titularId, auxiliarId );
		classroom.setId( id );
		
		nameTextField.setText( name );
		magazineTextFild.setText( magazine );
		titularComboBox.setSelectedItem( titular );
		auxiliarComboBox.setSelectedItem( auxiliar );
	}
}
